import axios from 'axios'
import { debounce, requestTimeout } from '@/config'
import store from '@/store'
import qs from 'qs'
import router from '@/router'
import { message } from 'ant-design-vue'

let loadingInstance

/**
 * @description axios初始化
 */
const instance = axios.create({
  timeout: requestTimeout,
})

function baseService(baseURL, headers, data) {
  // console.log(baseURL + data.url)
  // console.log(headers)
  // console.log(data)

  return instance({
    url: baseURL + data.url,
    method: data.method,
    params: data.params,
    data: data.data,
    headers: headers,
  })
}

/**
 * @description axios请求拦截器
 */

function request(data) {
  var headers = {
    'content-type': 'application/x-www-form-urlencoded',
  }
  // 待优化
  if (data.method === 'post' && data.headers === undefined) {
    data.data = qs.stringify(data.data)
  }
  if (data !== undefined && data.headers !== undefined) {
    headers = data.headers
  }
  if (debounce.some((item) => data.url.includes(item))) {
    //这里写加载动画
  }
  if (data.needToken) {
    const token = store.getters['user/accessToken']
    if (token) {
      headers['Authorization'] = 'Bearer ' + token
      return baseService('/agent', headers, data)
    } else {
      window.location.replace('/user/login')
    }
  } else {
    return baseService('/agent', headers, data)
  }
}

/**
 * @description axios响应拦截器
 */
instance.interceptors.response.use(
  (response) => {
    // console.log('响应拦截器', response)
    if (response.data.errorCode === 401) {
      console.log('响应拦截器', response)
      this.$router.push({
        name: 'login',
      })
    }
    if (!response.data) {
      response.data = {
        isSuccess: false,
        statuscode: 1001,
        content: null,
        errormessage: '没查到数据，可能是操作错了',
      }
    }
    return Promise.resolve(response.data)
  },
  (error) => {
    if (loadingInstance) loadingInstance.close()
    const { response, message } = error
    if (error.response && error.response.data) {
      const { status, data } = response
      handleCode(status, data.msg || message)
      return Promise.reject(error)
    } else {
      let { message } = error
      if (message === 'Network Error') {
        message = '后端接口连接异常'
      }
      if (message.includes('timeout')) {
        message = '后端接口请求超时'
      }
      if (message.includes('Request failed with status code')) {
        const code = message.substr(message.length - 3)
        message = '后端接口' + code + '异常'
      }
      message.error(message || `后端接口未知异常`)
      return Promise.reject(error)
    }
  }
)

/**
 * @description 处理code异常
 * @param {*} code
 * @param {*} msg
 */
const handleCode = (code, msg) => {
  switch (code) {
    case 401:
      message.error(msg || '登录失效')
      store.dispatch('user/resetAll').catch(() => {})
      break
    case 403:
      router
        .push({
          path: '/401',
        })
        .catch(() => {})
      break
    default:
      message.error(msg || `后端接口${code}异常`)
      break
  }
}

export default request
